import React, {
  useState,
  useRef,
  useImperativeHandle,
  forwardRef,
} from 'react';
import { Button, Form, Table } from 'antd';
import useMountData from '../../PublicHooks/useMountData';
import style from './index.less';

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};
const TitleForm = Form.create()(props => {
  const {
    getFieldDecorator,
    validateFieldsAndScroll,
    resetFields,
  } = props.form;
  const handleReset = e => resetFields();
  const handleSubmit = e => {
    e.preventDefault();
    e.stopPropagation();
    validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        props.search(values);
      }
    });
  };
  return (
    <Form
      {...formItemLayout}
      onSubmit={handleSubmit}
      className={style.titleForm}
    >
      {props.titleForm(getFieldDecorator)}
      <Form.Item wrapperCol={24}>
        <span className="padding-row">
          <Button size="large" type="primary" htmlType="submit">
            查询
          </Button>
        </span>
        {props.showReset && (
          <Button size="large" onClick={handleReset}>
            重置
          </Button>
        )}
      </Form.Item>
    </Form>
  );
});

const FormTable = (props, ref) => {
  const {
    dataSource,
    getData,
    titleForm,
    title,
    waitRun = false,
    showReset = false,
    pager: pagerProps,
    ...others
  } = props;

  const [loading, setLoading] = useState(false);
  const [pager, setPager] = useState({
    pageSize: 20,
    showSizeChanger: true,
    ...pagerProps,
  });
  const [params, setParams] = useState({ waitRun });

  const deps = [pager, params];
  const service = values => getData(values, setLoading);
  const data = useMountData(service, deps) || {
    Data: [],
    TotalCount: 0,
  };

  const handleTableChange = (pagination, filters, sorter) => {
    setPager({
      ...pager,
      ...pagination,
      PageIndex: pagination.current,
    });
  };

  const search = v => {
    setParams({
      ...v,
    });
  };
  const table = useRef(null);
  useImperativeHandle(ref, () => ({
    ...data,
  }));
  return (
    <Table
      ref={table}
      dataSource={data.Data}
      loading={loading}
      title={() => (
        <TitleForm
          search={search}
          titleForm={titleForm}
          showReset={showReset}
        />
      )}
      onChange={handleTableChange}
      pagination={{ total: data.TotalCount, ...pager }}
      {...others}
    />
  );
};

export default forwardRef(FormTable);
